<template>
	<view>
		<view class="cu-form-group" @click="addCycle">
			新增周期
		</view>
		
		<div class="" v-for="(item, index) in cycleList" :key="index" style="margin-top: 5px;">
			<view class="cu-form-group" @tap="toOkeList(item)">
				<div class="left-content">
					<div class="info">
						周期名：{{item.name}}
					</div>
					<div class="info">
						周期时间：{{item.startTime}} ~ {{item.endTime}}
					</div>
					<div class="info">
						周期状态：
						<span v-if="item.startTime > currentTime" style="color: blueviolet;">未开始</span>
						<span v-else-if="item.endTime >= currentTime && item.startTime <= currentTime" style="color: green;">进行中</span>
						<span v-else style="color: red;">已结束</span>
					</div>
				</div>
				<div class="right-content">
					<view class="cuIcon-delete " @tap.stop="delCycleById(item)" style="font-size: 18px;" v-if="staff.id == item.staffId"></view>
				</div>
			</view>
		</div>
		  
	</view>
</template>

<script>
	import iconfont from '../../font_4280116_f6izbgedf4m/iconfont.css';
	import request from '../../common/request';
	import common from 'common/common.js';
	export default {
		components:{
		},
		data() {
			return {
				leaderOkr: [], // 自己负责的okr的集合
				showLeaderOkr: 0, // 展示自己负责的okr
				selectedItem: 1, // 当前选中的项的索引
				type: 'center',
				showIndex:'',
				// 悬浮框
				horizontal: 'right',
				vertical: 'bottom',
				direction: 'horizontal',
				pattern: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#007AFF',
					buttonColor:"#007AFF"
				},
				staff:{},
				cycle:{},
				leader:{},
				nowDate:'',
				cycleList:[],
				okrMap:[],
				okrList:[],
				allOkrList:[],
				kr:{},
				// 选中的全部，方便判断
				selectedList:[],
				// 选择的kr
				selectedKrList:[],
				// 选择的okr
				selectedOkrList:[],
				// 选中的okr;
				okrSelect: {},
				// 已经选中了的alignment
				alignmentList:[],
				alignment:{},
				alignmentCycle:{},
				// 记录选择的list
				recordSelected:{},
				cycleId:'',
				returnContent:'',
				delBool: false,
			}
		},
		onLoad() {
			this.staff = uni.getStorageSync("staff");
			this.getAllCycle();
			// 获取当前时间
			const currentDate = new Date();
			this.nowDate = this.formatDate(currentDate);
			uni.removeStorageSync("ids");
			uni.removeStorageSync("leader");
		},
		onShow() {
			if(this.showLeaderOkr == 0){
				this.getAllCycle();
			} else if(this.showLeaderOkr == 1){
				this.getAllCycle();
				this.findOkrByLeader();
			}
		},
		computed: {
			// 获取当前时间
		    currentTime() {
				const currentDate = new Date();
				return this.formatDate(currentDate); // 获取当前时间
		    },
		},
		methods: {
			// 点击添加周期，跳转到添加页面
			addCycle(){
				uni.navigateTo({
					url: `/pages/okrs/addCycle`
				})
			},
			
			// 跳转到okrList
			toOkeList(cycle){
				uni.navigateTo({
					// url: `/pages/kr/globalView`,
					// url:'/pages/okr/okrList?okrList='+ encodeURIComponent(JSON.stringify(this.okrList))
					url: `/pages/okrs/okrList?cycleId=${cycle.id}`
				})
			},
			
			
			
			// 点击查看自己参与的okr
			findAllOkr(){
				if(this.showLeaderOkr == 1){
					this.getAllCycle();
					this.$refs.popup.close()
					this.showLeaderOkr = 0;
				} else{
					this.getAllCycle();
					this.$refs.popup.close()
				}
			},
			// 点击查看自己负责的okr
			findOkrByLeader(){
				var _this = this;
				request({
					url: common.api_base_url+'/okr/findOkrByLeader/' + _this.staff.id,
					data:{
					},
					method: 'GET',
					success: res => {
						_this.leaderOkr = res.data;
						_this.$refs.popup.close()
						_this.showLeaderOkr = 1;
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 元素的选中
			selectItem(index) {
			    this.selectedItem = index; // 设置当前选中的项
			},
			// 左侧组件
			toggle(type) {
				this.type = type
				// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
				this.$refs.popup.open(type)
			},
			// 跳转到全局视图
			toGolobalView(){
				uni.navigateTo({
					// url: `/pages/kr/globalView`,
					url:'/pages/kr/globalView?okrList='+ encodeURIComponent(JSON.stringify(this.okrList))
				})
			},
			// 通过周期id删除周期
			delCycleById(cycle){
				this.delBool = false;
				var _this = this;
				request({
					url: common.api_base_url+'/cycle/checkCompleted/' + cycle.id,
					data:{
					},
					method: 'GET',
					success: res => {
						this.delBool = res.data;
						if(this.delBool){
							this.returnContent = '您确定要删除这个周期吗？';
						} else{
							this.returnContent = "周期还有未完成任务，您确定要删除吗";
						}
						_this.delCycle();
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 删除周期
			delCycle(){
				uni.showModal({
				    title: '删除周期',
				    content: this.returnContent,
				    success: function (res) {
				        if (res.confirm) {
							request({
								url: common.api_base_url+'/cycle/' + cycle.id,
								data:{
								},
								method: 'DELETE',
								success: res => {
									_this.getAllCycle();
								},
								fail: function(e) {
									uni.showToast({
										title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
										icon:"loading"
									})
								},
							});
				        } else if (res.cancel) {
							res.cancel = true;
				        }
				    }
				});
			},
			// 选择okr的显示周期
			selectedCycle(cycle){
				this.cycle = cycle;
				this.okrList = this.okrMap[cycle.id];
				// this.$refs.cycleSelectPopupRef.close();// 或者 boolShow = false
			},
			// 显示okr的周期选中
			selectShowCycle(){
				// this.$refs.cycleSelectPopupRef.show();// 或者 boolShow = false
			},
			// 获取总进度
			calculateTotalProgress(krList) {
			      if (krList.length === 0) {
			        return 0;
			      }
			   // const totalProgress = (krList.reduce((sum, item) => sum + parseFloat(item.progress), 0) / krList.length);
		 
			   // 将结果转换为百分数形式，保留两位有效数字
			   // return totalProgress.toPrecision(2); // 4表示总位数，包括整数和小数位
			   return Number(krList.reduce((sum, item) => sum + parseFloat(item.progress), 0) / krList.length);
			},
			// 取消对齐
			cancleAlignment(){
				var _this = this;
				request({
					url: common.api_base_url+'/alignment/' + _this.alignment.id,
					data:{
					},
					method: 'DELETE',
					success: res => {
						_this.$refs.alignmentShowPopupRef.close();
						if(_this.showLeaderOkr == 0){
							_this.getOkrByStaffId();
						} else if(_this.showLeaderOkr == 1){
							_this.findOkrByLeader();
						}
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 点击对齐人，查看对齐详情
			alignmentDetail(alignment, index){
				this.showIndex = index;
				this.$refs.alignmentShowPopupRef.show(); // 或者 boolShow = rue
				this.alignment = alignment;
				this.cycleId  = this.cycle.id;
			},
			// 添加对齐
			addAlignment(){
				// 去空
				this.selectedList = this.selectedList.filter(item => item !== undefined && item !== null && item !== '');
				var _this = this;
				request({
					url: common.api_base_url+'/alignment/addAlignmentForOkr/' + _this.okr.id,
					data:{
						"alignmentList": _this.selectedList,
					},
					method: 'PUT',
					success: res => {
						_this.selectedList = [];
						if(_this.showLeaderOkr == 0){
							_this.getOkrByStaffId();
						} else if(_this.showLeaderOkr == 1){
							_this.findOkrByLeader();
						}
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 点击确定
			comsumSelect(){
				this.$refs.popupRef.close();
				this.addAlignment();
			},
			// 点击取消
			cancleSelcct(){
				this.$refs.popupRef.close();
			},
			// 选择周期
			selectCycle(cycle, index) {
				// 获取当前周期id
				uni.navigateTo({
					// url:'/pages/okrs/okrList?cycleId='+ encodeURIComponent(JSON.stringify(this.okrList))
					url: `/pages/okrs/okrList?cycleId=${cycle.id}`
				})
			},
			// 选中对标kr
			selectKR(okr) {
				// 当前okr对象
				if(okr.selected){
					// 选中了的，再点击，取消
					if(okr.parentId){
						// 说明是分任务
						this.selectedList[okr.parentId].selected = false;
						this.selectedList[okr.parentId] = null;
					} else {
						// 是okr主任务
						this.selectedList[okr.id].selected = false;
						this.selectedList[okr.id] = null;
					}
				} else{
					// 判断当前list里面有没有okr
					if(this.selectedList[okr.id] || this.selectedList[okr.parentId]){
						// 有，说明是切换
						okr.selected = true;
						if(okr.parentId){
							// 说明是分任务
							this.selectedList[okr.parentId].selected = false;
							this.selectedList[okr.parentId] = okr;
						} else {
							// 是okr主任务
							this.selectedList[okr.id].selected = false;
							this.selectedList[okr.id] = okr;
						}
					} else{
						// 无
						okr.selected = true;
						if(okr.parentId){
							// 说明是分任务
							this.selectedList[okr.parentId] = okr;
						} else {
							// 是okr主任务
							this.selectedList[okr.id] = okr;
						}
					}
				}
			},
			// 点击开启周期选择弹框
			chengeCycle(){
				
				this.$refs.cyclePopupRef.show(); // 或者 boolShow = rue
			},
			// 回显
			showBackAlignment(){
				// 做回显
				if(this.alignmentList){
					for (const alignment of this.alignmentList) {
						for (const key in this.allOkrGroup) {
						// 	// 遍历一个周期
							if(alignment.cycleId == key){
								// 当前周期下所有数据
								var okrList = this.allOkrGroup[key]
								for (const okr of okrList) {
									
									if (alignment.parentId) {
										
										// 如果存在，说明是子任务
										for (const kr of okr.subOkrList) {
											if (alignment.targetId === kr.id) {
												// 判断是哪一个子任务
												kr.selected = true;
												// 设置回selectedKrList
												this.selectedList[kr.parentId] = kr;
											}
										}
									} else {
										if (alignment.targetId === okr.id) {
											  // 这里是okr
											  okr.selected = true;
											  // 设置回selectedOkrList
											  this.selectedList[okr.id] = okr;
										}
									}
								}
								
							}
						  
						}
					}
				}
			},
			// 点击开启KR选择弹框，添加对齐
			selectAlignment(item){
				// 点击对齐按钮之后，展示的周期
				this.alignmentCycle = this.cycleList[0]
				
				this.alignmentList = item.alignmentList;
				this.cycleId  = this.cycle.id;
				
				this.getAllOkrGroupBycycleId();
				this.okr = item;
				
				this.$refs.popupRef.show(); // 或者 boolShow = rue
			},
			// 获取当前周期所有OKR，用来对齐
			getAllOkrGroupBycycleId(){
				var _this = this;
				request({
					url: common.api_base_url+'/okr/getAllOkrGroupBycycleId',
					data:{
					},
					method: 'GET',
					success: res => {
						_this.allOkrGroup = res.data;
						_this.allOkrList = _this.allOkrGroup[_this.alignmentCycle.id];
						_this.showBackAlignment();
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// okr详情
			okrDetail(okr){
				this.cycleId = this.cycle.id;
				uni.navigateTo({
					url:'/pages/okrs/okrDetail?okr='+ encodeURIComponent(JSON.stringify(okr)),
				})
			},
			// 编辑okr
			updateOkr(okr){
				this.cycleId = this.cycle.id;
				uni.navigateTo({
					// url: `/pages/okrs/addOkr?cycleId=${this.cycle.id}`,
					url:'/pages/okrs/addOkr?okr='+ encodeURIComponent(JSON.stringify(okr)),
				})
			},
			// 获取当前用户有关的okr
			getOkrByStaffId(){
				var _this = this;
				request({
					url: common.api_base_url+'/okr/getOkrByStaffId/' + _this.staff.id,
					// url: common.api_base_url+'/okr/getOkrByStaffId/' + 20,
					data:{
					},
					method: 'GET',
					success: res => {
						_this.okrMap = res.data;
						_this.okrList = _this.okrMap[_this.cycleId];
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 时间转换格式方法
			formatDate(date) {
			  const year = date.getFullYear();
			  const month = String(date.getMonth() + 1).padStart(2, '0');
			  const day = String(date.getDate()).padStart(2, '0');
			  return `${year}-${month}-${day}`;
			},
			// 计算当前时间
			calculateDifference(cycle, nowDate){
				var endTime = new Date(cycle.endTime);
				var nowDate = new Date(nowDate);
				var startTime = new Date(cycle.startTime);
				if(startTime > nowDate){
					return "未开始";
				} else if(startTime <= nowDate && nowDate <= endTime){
					// 计算日期差值（以天为单位）
					var diffDays = Math.abs(endTime - nowDate) / (1000 * 3600 * 24);
					// 使用Math.ceil()函数向上取整
					var roundedDiffDays = Math.ceil(diffDays); 
					return "还剩" + roundedDiffDays + "天";
				} else{
					return "已结束";
				}
			},
			// 周期字体颜色
			 getStatusColor(cycle, nowDate) {
			      const status = this.calculateDifference(cycle, nowDate);
			      if (status === "未开始") {
			        return "unstarted-color"; // 未开始状态的类名
			      } else if (status === "已结束") {
			        return "finished-color"; // 已结束状态的类名
			      } else {
			        return "in-progress-color"; // 进行中状态的类名
			      }
			    },
			// 获取所有周期
			getAllCycle(){
				var _this = this;
				request({
					url: common.api_base_url+'/cycle',
					data:{
					},
					method: 'GET',
					success: res => {
						_this.cycleList = res.data;
						if(_this.cycleId){
							_this.cycleId =  _this.cycleList.findIndex(e => e.id == _this.cycleId);
							if(_this.cycleId < 0 ){
								_this.cycleId = 0;
							}
							_this.cycle = _this.cycleList[_this.cycleId];
							_this.cycleId = _this.cycle.id;
						}else{
							_this.cycle = _this.cycleList[0];
							_this.cycleId = _this.cycle.id;
						}
						if(_this.showLeaderOkr == 0){
							// _this.getOkrByStaffId();
						}
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 悬浮框点击事件，跳转到okr添加页面
			fabClick(){
				this.cycle.id = this.cycleId;
				uni.navigateTo({
					// url: `/pages/okrs/addOkr?cycleId=${this.cycle.id}`,
					url:'/pages/okrs/addOkr?data='+ encodeURIComponent(JSON.stringify(this.cycle)),
				})
			},
			
		}
	}
</script>

<style scoped>
	.scroll-page {
	  height: 100vh;
	}
	
	.scroll-view {
	  height: 100%;
	}
	
	.content {
	  padding: 10px;
	}
	
	.item {
	  height: 50px;
	  line-height: 50px;
	  background-color: #f0f0f0;
	  margin-bottom: 10px;
	  text-align: center;
	}
	
	.selected {
	  border: 2px solid red; /* 选中时的红色边框 */
	}
	/* 两个按钮样式 */
	.button-container {
	  display: flex;
	  justify-content: space-between;
	}
	
	button {
	  size: 30px;
	  flex: 1;
	  border-radius: 20px;
	  border: none;
	  text-align: center;
	  font-size: 13px;
	  width: 15px;
	  height: 30px;
	  padding-left: unset;
	  padding-right: unset;
	}
	

	
	/* 设置确定按钮的背景颜色为蓝色 */
	.confirm-button {
	  background-color: blue;
	  color: white;
	}
	
	.alignment-container {
	  display: flex;
	  align-items: center; /* 垂直居中对齐 */
	}
	
	.alignment-row {
	  display: inline-block;
	  margin-right: 10px; /* 可以添加一些右侧间距，根据需要调整 */
	}
	
	
	/* cs */
	.item-container {
	  display: flex; /* 使用Flex布局 */
	  align-items: center; /* 垂直居中对齐 */
	}
	
	.progress-text,
	.progress-circle,
	.leader-name {
	  margin-right: 20px; /* 为各元素之间添加间距，可以根据需要调整 */
	}
	
	/* cs */
	.cu-form-group {
	    display: flex;
	    align-items: center; /* 垂直居中 */
	}
	
	.left-content {
	   /* flex: 80%; */
	}
	
	.right-content {
	    /* flex: 20%; */
	    display: flex;
	    justify-content: flex-end; /* 右侧内容右对齐 */
	}
	
	.unstarted-color {
	  color: blueviolet; /* 进行中状态的字体颜色 */
	}
	
	.in-progress-color {
	  color: green; /* 已结束状态的字体颜色 */
	}
	
	.finished-color {
	  color: red; /* 未开始状态的字体颜色 */
	}
	
	.container {
	  display: flex;
	  justify-content: space-between;
	  background-color: white;
	}
	
	.item {
	  /* 左边元素的样式 */
	  /* flex-grow: 1;  */
	  padding: 5px;
	  /* border: 1px solid #ccc; */
	  background-color: white;
	  margin-bottom: unset;
	}
	
	.right {
	  /* 右边元素的样式 */
	  margin-left: auto; /* 使用 margin-left: auto; 将其推到右边 */
	}
	.uni-view{
		width: 80%;
	}

	.viewSelected {
	  display: block;
	  margin-bottom: 10px; /* 垂直间距 */
	}
	
	.selected {
	  color: red; /* 选中时的颜色 */
	}

</style>
